package com.younion.business.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.younion.business.IMsgTemplateService;
import com.younion.common.constants.PlateformType;
import com.younion.common.constants.Status;
import com.younion.common.paginator.Paginator;
import com.younion.dao.CustomerDAO;
import com.younion.dao.MsgTemplateDAO;
import com.younion.permission.PermissionUtil;
import com.younion.vo.CustomerVO;
import com.younion.vo.MsgTemplateVO;

import cpcns.component.common.base.BaseException;
import cpcns.jhsks.util.MapCollectionUtils;

 
public class MsgTemplateServiceImpl extends BaseService implements IMsgTemplateService {

	protected static final Log logger = LogFactory.getLog(MsgTemplateServiceImpl.class);

	private MsgTemplateDAO msgTemplateDAO;
	@Autowired
	private CustomerDAO customerDAO;
	
	public Collection getAll() throws Exception {
		return msgTemplateDAO.selectAll();
	}

	public MsgTemplateVO getById(String id) throws Exception {
		if (StringUtils.isEmpty(id) || Integer.parseInt(id)<1)
			return null;
		try {
			Map paramMap = new HashMap();
			paramMap.put("id", new Integer(id));
			Object obj = msgTemplateDAO.selectById(paramMap);
			return obj==null?null:(MsgTemplateVO)obj;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public MsgTemplateVO get(String id) error occur:",e);
		}
	}
	public Collection getByMap(Map paramMap) throws BaseException {
		if(CollectionUtils.isEmpty(paramMap)){
			return null;
		}
		try{
			return msgTemplateDAO.selectByMap(paramMap);
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public Collection getByMap(Map map) error occur:",e);
		}
	}

	public int getCountByMap(Map paramMap) throws BaseException {
		try {
			return msgTemplateDAO.selectCountByMap(paramMap);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()
					+ " >> public Collection getCountByMap(Map map) error occur:", e);
		}
	}

	public List get(Map paramMap, Paginator paginator) throws Exception {
		if (MapCollectionUtils.isEmpty(paramMap)) {
			return null;
		}
		try {
			Map map = new HashMap();
			map.put("paramMap", paramMap);
			return msgTemplateDAO.selectForPage(map, paginator);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public Page (Map paramMap, Paginator paginator) error occur:",e);
		}
	}

	public MsgTemplateVO save(MsgTemplateVO voObject) throws Exception {
		if (voObject == null)
			return null;
		try {
			Object id = null;
			id = voObject.getId();
			Map paramMap = MapCollectionUtils.removeEmptyEntry(PropertyUtils.describe(voObject));
			if (id != null) {
				msgTemplateDAO.updateByMap(paramMap);
				return voObject;
			} else {
				if(SecurityUtils.getSubject().isPermitted("AddPlateformTypeMsg")){
					voObject.setPlateformType(PlateformType.PLATEFORM.getName());
					voObject.setStatus(Status.ACTIVE.getName());
				}else{
					voObject.setPlateformType(PlateformType.CUSTOM.getName());
					voObject.setStatus(Status.UNACTIVE.getName());
				}
				return (MsgTemplateVO)msgTemplateDAO.insertByVo(voObject);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public MsgTemplateVO save(MsgTemplateVO voObject) error occur:",e);
		}
	}

	public Collection save(Collection voList) throws Exception {
		if (CollectionUtils.isEmpty(voList))
			return null;
		try {
			Iterator it = voList.iterator();
			while (it.hasNext()) {
				MsgTemplateVO data = (MsgTemplateVO) it.next();
				data = save(data);
			}
			return voList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public Collection save(Collection voList) error occur:",e);
		}
	}

	public boolean remove(List ids) throws Exception {
		if (CollectionUtils.isEmpty(ids))
			return false;
		try{
			msgTemplateDAO.deleteByIds(ids);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public boolean remove(List ids) error occur:",e);
		}
	}

	public boolean removeByMap(Map paramMap) throws Exception {
		if (CollectionUtils.isEmpty(paramMap))
			return false;
		try {
			msgTemplateDAO.deleteByMap(paramMap);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public boolean removeByMap(Map paramMap) error occur:",e);
		}
	}
	
	public String generateCustomerNames(String ids) throws Exception {
		List<String> names = Lists.newArrayList();
		try{
			List params = Arrays.asList(ids.split(PermissionUtil.comma));
			List<CustomerVO> customers =  customerDAO.selectByIds(params);
			for(CustomerVO c : customers){
				names.add(c.getName());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return StringUtils.join(names, PermissionUtil.comma);
	}
	
	public boolean updateStatus(List ids,String status) throws Exception {
		if (CollectionUtils.isEmpty(ids))
			return false;
		try{
			msgTemplateDAO.updateStatusByIds(ids,status);
			return true;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public boolean approve(List ids) error occur:",e);
		}
	}
	
	public void updateCustomerIds(List<String> customerIds) throws BaseException{
		try{
			List<MsgTemplateVO> list = new ArrayList<MsgTemplateVO>();
			for(String customerId : customerIds){
				Map<String,String> paramMap = new HashMap<String,String>();
				paramMap.put("customerId", customerId);
				List<MsgTemplateVO> templateList = (List<MsgTemplateVO>) msgTemplateDAO.selectByMap(paramMap);
					for(MsgTemplateVO template : templateList){
						String customerIds_str = template.getCustomerIds();
						String[] customerId_str = customerIds_str.split(",");
						String customerIds_new = new String();
						for(int i = 0;i<customerId_str.length;i++){
							if(!customerId_str[i].equals(customerId)){
								customerIds_new+=customerId_str[i];
								if(i!=customerId_str.length-1){
									customerIds_new+=",";
								}
							}
						}
						template.setCustomerIds(customerIds_new);
						list.add(template);
					}
				paramMap.clear();
				
			}
			save(list);
		}catch(Exception e){
			logger.error(e.getMessage(), e);
			throw new BaseException(MsgTemplateServiceImpl.class.getName()+" >> public void updateCustomerIds(List<String> customerIds) error occur:",e);
		}
		
	}
	
	/**
	 * @param service
	 */
	public void setMsgTemplateDAO(MsgTemplateDAO msgTemplateDAO) {
		this.msgTemplateDAO = msgTemplateDAO;
	}

	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}
	
	 public List selectByIds(List ids) throws Exception{
		 return msgTemplateDAO.selectByIds(ids);
	 }
	
}